const { db } = require("../../db/db2");
/**
 * 同步用户点赞的沸点信息到redis中
 */
async function snycUserLikePins(userId) {
  const userLikedKey = `Pin:${userId}:users`;
  const isCached = await redis.exists(userLikedKey);

  if (!isCached) {
    // 如果 Redis 缓存中不存在，则查询数据库并同步到 Redis
    const [rows] = await db
      .promise()
      .query("SELECT PinId FROM PinLike WHERE UserId = ?", [userId]);

    const articleIds = rows.map((row) => row.PinId);
    if (articleIds.length > 0) {
      await redis.sadd(userLikedKey, articleIds); // 将用户的点赞记录同步到 Redis
    }

    console.log(`User ${userId} likes synchronized to Redis`);
  }

  // 返回 Redis 中的点赞记录
  return await redis.smembers(userLikedKey);
}

module.exports = { snycUserLikePins };
